package cn.xuexiyuan.springstudy.core.demo04.service;

import cn.xuexiyuan.springstudy.core.demo04.entity.AbstractPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 使用 @Autowired 注解分别使用在 字段、 setter 方法、构造方法上实现 POJO 的自动装配。
 * @Autowired 注解也可以是其他任意方法。
 *
 *
 */
@Service
public class SequenceGenerator {
    private final AtomicInteger counter = new AtomicInteger();

    private AbstractPrefix defaultPrefix;

    private List<AbstractPrefix> prefixs;

    @Autowired
    private Map<String, AbstractPrefix> prefixMap;


    @Autowired
    public SequenceGenerator(AbstractPrefix defaultPrefix) {
        this.defaultPrefix = defaultPrefix;
    }


    @Autowired
    public void setPrefixs(List<AbstractPrefix> prefixs) {
        this.prefixs = prefixs;
    }

    public String getSequence(){
        StringBuilder builder = new StringBuilder();
        builder.append(defaultPrefix.getPrefix()).append(counter.getAndIncrement());

        return builder.toString();
    }

    public String getSequence(Class prefix){
        StringBuilder builder = new StringBuilder();
        for(AbstractPrefix p : prefixs){
            if(prefix.equals(p.getClass())){
                builder.append(p.getPrefix());
                break;
            }
        }
        builder.append(counter.getAndIncrement());

        return builder.toString();
    }


    public void printPrefix(){
        System.out.println(prefixMap);
    }
}
